var fs = require('fs');
var net = require('net');
var fileName = './tts.mp3';
var fileBuf = fs.readFileSync(fileName);
var initBuf = 1024;
console.log("file total size "+ fileBuf.length);

uMask = "这是个随机的字符串";
var uMagic = parseInt(Math.random()*10000,10)+1;

var serverHost = "192.168.1.199";
var serverPort = 6002;

var seed_code = "sn序列号"; 


if (seed_code.length !=32 ){
	
	console.log("SN设备序列号不合法,清核对~~~")
	
	return
}



var client = new net.Socket();
client.connect(serverPort, serverHost, function() 
{
    console.log('Connected');
    console.log('CONNECTED TO:' + serverHost + ':' + serverPort);
    json_content = '{"cmd":"PLAYLIST","ulevel":99,"plevel":2,"Umask":"'+uMask+'","Umagic":'+uMagic+',"snlist":["'+seed_code+'"]}';
    json_len = json_content.length
    // console.log(json_len.toString()+'\n'+json_content);
    client.write(json_len.toString()+'\n'+json_content);

    console.log('初始化消息队列~~~~');
    client.write(new Buffer.alloc(initBuf,'init','base64'));
    //console.log(new Buffer.alloc(initBuf,'init','base64'));
    sleep(1000);

});

function sleep(sleepTime){
    for(var start = +new Date; +new Date - start <= sleepTime; ) { } 
}

var t;
var j = 0; 
totalPackageSize = 0;

function  send_data(){
    var packetSize = 1024;
			
    	var packetContent = fileBuf.slice(totalPackageSize,packetSize+totalPackageSize);
    	console.log(fileBuf.length+" ----> "+packetContent.length);
    	totalPackageSize = totalPackageSize + packetSize;

        j++;	

	if(client.write(packetContent)){
		console.log("the ",j," package is send over,go Next~~");
	}else{
		clearInterval(t);
		client.destroy();
	}
	 
	if(j >= fileBuf.length/packetSize ){
                client.write(new Buffer.alloc(initBuf,'init','base64'));
                sleep(1000);
                clearInterval(t);
		client.destroy();
	}
}
client.on('data', function(data) {
    console.log('Received: '+ data);
	if(data == "WELL"){
		t = setInterval(send_data,63);
		console.log("content wait for send:"+fileBuf.length);	

	}else if(data == "DISS") {
             client.destroy();
	}
});

client.on('close', function() {
    console.log('Connection closed');
    clearInterval(t);
});
client.on('error', function(err) {
    console.error('Socket error: ' + err );
    console.error(new Error().stack);
	clearInterval(t);
});
